package com.whitecat.voting;

import com.whitecat.voting.constant.SysConstant;
import com.whitecat.voting.util.MaterialUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Collection;

@Slf4j
@Component
public class ScreenshotJob {

    @Scheduled(cron = "0 0/1 * * * ?")
    public void generateCoverImgIfAbsent() {
        File materialDir = FileUtils.getFile(System.getProperty("user.dir"), SysConstant.DEFAULT_MATERIAL_DIR);
        Collection<File> videos = FileUtils.listFiles(materialDir, new String[]{"mp4"}, true);
        for (File video : videos) {
            File parentDir = video.getParentFile();
            File screenshot = FileUtils.getFile(parentDir, "screenshot.jpeg");
            if (!screenshot.exists()) {
                log.info("generating screenshot [{}]", screenshot.getAbsolutePath());
                MaterialUtils.extractScreenshot(video);
            }

            File thumb = FileUtils.getFile(parentDir, "thumb.jpeg");
            if (!thumb.exists()) {
                log.info("generating thumb [{}]", thumb.getAbsolutePath());
                MaterialUtils.scaleImage(screenshot, 0.5);
            }
        }
    }
}
